package ch02.LL_K_Parser;

public class LookaheadParser extends Parser{
    public LookaheadParser(Lexer input, int k) {
        super(input, k);
    }

    /** element : NAME '=' NAME | NAME | LIST ; assignment, NAME or list */
    void element() {
        // 同时向前看2个字符， 判断是否为赋值语句
        if (LA(1) == LookaheadLexer.NAME && LA(2) == LookaheadLexer.EQUALS) {
            match(LookaheadLexer.NAME);
            match(LookaheadLexer.EQUALS);
            match(LookaheadLexer.NAME);
        } else if (LA(1) == LookaheadLexer.NAME) {
            match(LookaheadLexer.NAME);
        } else if (LA(1) == LookaheadLexer.LBRACK) {
            list();
        } else {
            throw new Error("expecting name or list; found " + LT(1));
        }
    }

    /** list : '[' elements ']' ;  // 匹配方括号 */
    void list() {
        match(LookaheadLexer.LBRACK);       // 期望 [
        elements();                         // 期望 elements
        match(LookaheadLexer.RBRACK);       // 期望 ]
    }


    /** elements : element (',' element)* ; // 匹配逗号分割的list */
    void elements() {
        element();
        while (LA(1) == LookaheadLexer.COMMA) {
            match(LookaheadLexer.COMMA);
            element();
        }
    }
}
